import store from "@/store";
import version from "@/version";
import utils from "./utils";
// platform可选值 wechat: 微信, alipay: 支付宝, bytedance: 字节跳动

// 正常提交 start

// const store_id = 84; // 平台小程序为0，独立小程序填对应的store_id
// let platform;
// //#ifndef MP-ALIPAY
// platform = "wechat";
// //#endif
// //#ifdef MP-ALIPAY
// platform = "alipay";
// //#endif
// //#ifdef MP-TOUTIAO
// platform = "bytedance";
// //#endif
// //#ifdef APP-PLUS
// platform = "app";
// //#endif
// //#ifdef WEB
// platform = "h5";
// //#endif
// let is_single_store = "no";
// if (store.getters.has_is_one_store) {
//   is_single_store = "yes";
// }
// // #ifndef H5
// const API_URL = (url) => {
//   return `https://chidian.chixiaodian.com/index.php?r=client/v1${url}&is_single_store=${is_single_store}&platform=${platform}&version=${version.version}`;
// };
// // #endif

// 正常提交 end

// 模板提交 start

let extConfig = uni.getExtConfigSync ? uni.getExtConfigSync() : {};
// #ifdef MP-TOUTIAO
extConfig = extConfig.extConfig;
// #endif

const store_id = extConfig.store_id;
let platform;
//#ifndef MP-ALIPAY
platform = "wechat";
//#endif
//#ifdef MP-ALIPAY
platform = "alipay";
//#endif
//#ifdef MP-TOUTIAO
platform = "bytedance";
//#endif
//#ifdef APP-PLUS
platform = "app";
//#endif
const is_isv = "yes";

let mini_id = extConfig.mini_id;
let self_mini = extConfig.self_mini ? 1 : 0;
const API_URL = (url) => {
  return `${extConfig.apiurl}/index.php?r=client/v1${url}&self_mini=${self_mini}&platform=${platform}&is_isv=${is_isv}&mini_id=${mini_id}&version=${version.version}`;
};

// 模板提交 end

// // #ifdef H5
// const API_URL = (url) => {
//   return `https://chidian.chixiaodian.com/index.php?r=client/v1${url}&_form=h5&platform=${platform}&version=${version.version}`;
// };
// // #endif

function setMdId(params) {
	let active=0
	if(params&&params.newMd_id){
		active=1
	}
	let mdLocalData = uni.getStorageSync("storeMdData");
	if (mdLocalData) {
	  let mdData = {};
	  if (typeof mdLocalData == "string" && Object.keys(mdLocalData)) {
	    mdData = JSON.parse(mdLocalData);
	  }
	  if (mdData?.id&&active==0) {
	    params = { md_id: mdData.id, ...params };
	  }
	}

  if (params) {
    // #ifdef WEB
    params._from = utils.isWechat() ? "official" : "h5";
    // #endif
  }

  return params;
}

function getStoreId() {
  if (store.getters.has_is_one_store && !uni.getStorageSync("store_id")) {
    store.commit("setStoreId", "0");
  }
  const storeId = uni.getStorageSync("store_id");

  return storeId ? storeId : store_id;
}

function POST(url, params, needLoading, showMsg = true) {
  const Token = uni.getStorageSync("token");
  if (needLoading) {
    uni.showLoading({
      title: "加载中",
      mask: true
    });
  }

  let header = {
    "content-Type": "application/x-www-form-urlencoded"
  };
  let storeAdminToken = uni.getStorageSync("storeAdminToken");
  if (storeAdminToken) {
    header = {
      ...header,
      Authorization: storeAdminToken
    };
  }
  let promise = new Promise(function (resolve, reject) {
    params = setMdId(params);
    uni.request({
      url: API_URL(url),
      method: "POST",
      data: {
        ...params,
        access_token: Token,
        store_id: getStoreId()
      },
      header,
      success: (res) => {
        if (res.data.code == 401) {
          uni.removeStorageSync("hasUri");

          let routes = getCurrentPages();
          if (routes.length > 0) {
            store.commit(
              "setNoLoginTabarPath",
              routes[routes.length - 1].$page.fullPath
            );
            store.commit("setRouteType", "redirectTo");
          }
          uni.redirectTo({
            url: "/login/login/login_page"
          });
        } else if (res.data.code == 0) {
          if (res.data.status && res.data.status === 401) {
            uni.reLaunch({
              url: "/admin/login/login"
            });
          } else {
            resolve(res.data);
          }
        } else if (res.data.code == 402) {
          uni.reLaunch({
            url: "/other/register/index"
          });
        } else {
          reject(res.data);
          if (res.data.msg && showMsg) {
            setTimeout(() => {
              if (res.data.msg.length < 20) {
                uni.showToast({
                  title: res.data.msg,
                  duration: 2000,
                  icon: "none"
                });
              } else {
                uni.showModal({
                  content: res.data.msg,
                  showCancel: false,
                  confirmText: "知道了"
                });
              }
            }, 100);
          }
        }
        // resolve(res.data);
      },
      fail: (res) => {
        reject(res.data);
      },
      // 完成之后关闭加载效果
      complete: () => {
        if (needLoading) {
          uni.hideLoading();
        }
      }
    });
  });
  return promise;
}

function POSTJSON(url, params, needLoading) {
  const Token = uni.getStorageSync("token");
  if (needLoading) {
    uni.showLoading({
      title: "加载中",
      mask: true
    });
  }
  let header = {
    "content-Type": "application/json"
  };
  let storeAdminToken = uni.getStorageSync("storeAdminToken");
  if (storeAdminToken) {
    header = {
      ...header,
      Authorization: storeAdminToken
    };
  }

  let promise = new Promise(function (resolve, reject) {
    params = setMdId(params);
    uni.request({
      url: API_URL(url),
      method: "POST",
      data: {
        ...params,
        access_token: Token,
        store_id: getStoreId()
      },
      header,
      success: (res) => {
        if (res.data.code == 401) {
          uni.removeStorageSync("hasUri");

          let routes = getCurrentPages();
          if (routes.length > 0) {
            store.commit(
              "setNoLoginTabarPath",
              routes[routes.length - 1].$page.fullPath
            );
            store.commit("setRouteType", "redirectTo");
          }
          uni.redirectTo({
            url: "/login/login/login_page"
          });
        } else if (res.data.code == 0 || res.data.code == -1) {
          if (res.data.status && res.data.status === 401) {
            uni.reLaunch({
              url: "/admin/login/login"
            });
          } else if (res.data.code == 402) {
            uni.redirectTo({
              url: "/other/register/index"
            });
          } else {
            resolve(res.data);
          }
        } else if (res.data.code == 402) {
          uni.reLaunch({
            url: "/other/register/index"
          });
        } else {
          reject(res.data);
          if (res.data.msg) {
            setTimeout(() => {
              uni.showToast({
                title: res.data.msg,
                duration: 2000,
                icon: "none"
              });
            }, 100);
          }
        }
      },
      fail: (res) => {
        reject(res.data);
      },
      // 完成之后关闭加载效果
      complete: () => {
        if (needLoading) {
          uni.hideLoading();
        }
      }
    });
  });
  return promise;
}

function GET(url, params, needLoading, hideLoading = true) {
  const Token = uni.getStorageSync("token");
  if (needLoading) {
    uni.showLoading({
      title: "加载中",
      mask: true
    });
  }

  let header = {
    "content-Type": "application/x-www-form-urlencoded"
  };
  let storeAdminToken = uni.getStorageSync("storeAdminToken");
  if (storeAdminToken) {
    header = {
      ...header,
      Authorization: storeAdminToken
    };
  }

  let promise = new Promise(function (resolve, reject) {
    params = setMdId(params);

    uni.request({
      url: API_URL(url),
      method: "GET",
      data: {
        show_shenhe: store.getters["shenheStatus"],
        access_token: Token,
        ...params,
        store_id: getStoreId(),
      },
      header,
      success: (res) => {
        if (res.data.code == 401) {
          uni.removeStorageSync("hasUri");

          let routes = getCurrentPages();
          if (routes.length > 0) {
            store.commit(
              "setNoLoginTabarPath",
              routes[routes.length - 1].$page.fullPath
            );
            store.commit("setRouteType", "redirectTo");
          }
          uni.redirectTo({
            url: "/login/login/login_page"
          });
        } else if (res.data.code == 0) {
          if (res.data.status && res.data.status === 401) {
            uni.reLaunch({
              url: "/admin/login/login"
            });
          } else {
            resolve(res.data);
          }
        } else if (res.data.code == 402) {
          uni.reLaunch({
            url: "/other/register/index"
          });
        } else {
          reject(res.data);
          if (res.data.msg) {
            setTimeout(() => {
              uni.showToast({
                title: res.data.msg,
                duration: 2000,
                icon: "none"
              });
            }, 100);
          }
        }
      },
      fail: (res) => {
        if (res.code != 0) {
          uni.showToast({
            title: res.msg,
            icon: "none",
            duration: 3000
          });
        }
        reject(res.data);
      },
      // 完成之后关闭加载效果
      complete: () => {
        if (needLoading) {
          uni.hideLoading();
        }
      }
    });
  });
  return promise;
}

function GETPoster(url, params, hide_loading) {
  const Token = uni.getStorageSync("token");
  if (hide_loading != true) {
    uni.showLoading({
      title: "加载中",
      mask: true
    });
  }

  let header = {
    "content-Type": "application/x-www-form-urlencoded"
  };
  let storeAdminToken = uni.getStorageSync("storeAdminToken");
  if (storeAdminToken) {
    header = {
      ...header,
      Authorization: storeAdminToken
    };
  }

  let promise = new Promise(function (resolve, reject) {
    params = setMdId(params);
    uni.request({
      url: API_URL(url),
      method: "GET",
      data: {
        ...params,
        access_token: Token,
        store_id: getStoreId()
      },
      header,
      success: (res) => {
        if (res.data.code == 401) {
          uni.removeStorageSync("hasUri");

          uni.redirectTo({
            url: "/login/login/login_page"
          });
        } else if (res.data.code == 0 || res.data.code == 1) {
          if (res.data.status && res.data.status === 401) {
            uni.reLaunch({
              url: "/admin/login/login"
            });
          } else {
            resolve(res.data);
          }
        } else if (res.data.code == 402) {
          uni.reLaunch({
            url: "/other/register/index"
          });
        } else {
          uni.showToast({
            title: res.data.msg || "服务器出错",
            duration: 3000,
            icon: "none",
            complete: () => {
              reject(res.data);
            }
          });
        }
      },
      fail: (res) => {
        if (res.code != 0) {
          uni.showToast({
            title: res.msg,
            icon: "none",
            duration: 3000
          });
        }
        reject(res.data);
      },
      // 完成之后关闭加载效果
      complete: () => {
        if (hide_loading) {
          uni.hideLoading();
        }
      }
    });
  });
  return promise;
}

function UPLOAD_IMAGE(tempFilePaths, success, formData = {}) {
  const url = API_URL("/upload/upload-image");
  uni.uploadFile({
    url: url,
    filePath: tempFilePaths,
    name: "image",
    formData: {
      ...formData,
      store_id: getStoreId()
    },
    success: (uploadFileRes) => {
      uploadFileRes = JSON.parse(uploadFileRes.data);
      success(uploadFileRes);
    },
    fail: (res) => {
      uni.hideLoading();
    }
  });
}
function UPLOAD_VIDEO(tempFilePaths, success, formData = {}) {
  const url = API_URL("/upload/upload-video");

  uni.showLoading({
    title: "请稍等",
    mask: true
  });

  uni.uploadFile({
    url: url,
    filePath: tempFilePaths,
    name: "video",
    timeout: 60000 * 5,
    formData: {
      ...formData,
      store_id: getStoreId()
    },
    success: (uploadFileRes) => {
      uploadFileRes = JSON.parse(uploadFileRes.data);
      success(uploadFileRes);
    },
    complete: () => {
      uni.hideLoading();
    }
  });
}
export default {
  GETPoster,
  POST,
  POSTJSON,
  GET,
  UPLOAD_IMAGE,
  UPLOAD_VIDEO,
  API_URL,
  getToken: function () {
    return uni.getStorageSync("token");
  },
  getUser: function () {
    return uni.getStorageSync("User");
  },
  getStoreId
};
